package com.longyiqun.cm;

import com.google.common.base.Charsets;
import com.google.common.hash.HashCode;
import com.google.common.hash.Hashing;
import com.google.gson.*;
import com.longyiqun.cm.domain.TestCaseEntity;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import org.apache.commons.lang.StringUtils;

import static io.restassured.RestAssured.given;


/**
 * program: CaseManager
 * package: com.longyiqun.cm
 * author: 龙轶群
 * create: 2018-04-02 11:33
 **/
public class MockServer {

    public static String mock(TestCaseEntity c, String env) {

        // 获取Case基本信息
        String isSign = "";
        String caseMethod = c.getMethod();
        if (c.getSignature() != null) {
            isSign = c.getSignature();
        } else {
            isSign = "off";
        }

        // 判断是POST还是GET请求, 如有其它method, 待扩展
        if (caseMethod.toUpperCase().equals("POST")) {

            // 判断是否验签
            if (isSign.equals("on")) {
                return PostWithSignature(c, env);
            } else {
                return PostWithOutSignature(c, env);
            }

        } else if (caseMethod.toUpperCase().equals("GET")) {
            if (isSign.equals("on")) {
                return GetWithSignature(c, env);
            } else {
                return GetWithOutSignature(c, env);
            }
        } else {
            return "";
        }
    }

    // Post方法, 有验签
    private static String PostWithSignature (TestCaseEntity c, String env) {
        // 获取Case信息
        String postBody = c.getBody();
        String caseModel = c.getModule();
        String url = TestServer.getURL(caseModel, env) + c.getUrl();
        String tokenAnduid;
        System.out.println(caseModel+"      module");

        tokenAnduid = userLoginReturnToken(caseModel, env);

        String token = tokenAnduid.split(",")[0];
        String uid = tokenAnduid.split(",")[1];

        // 验签规则 - 1
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("AppKey", Constants.WODA_AppKey);
        jsonObject.addProperty("Data", postBody);
        jsonObject.addProperty("DeviceName", Constants.WODA_DeviceName);
        jsonObject.addProperty("DeviceType", Constants.WODA_DeviceType);
        jsonObject.addProperty("Lang", Constants.WODA_Lang);
        long time = System.currentTimeMillis();
        String signValue = "WDApp" + time/1000 + "" + postBody + "a323f9b6-1f04-420e-adb9-b06d142c5e63";
        System.out.println(signValue);
        String signValueMD5 = converToMD5(signValue);
        System.out.println(signValueMD5);

        jsonObject.addProperty("Sign", signValueMD5);
        jsonObject.addProperty("Token", token);
        jsonObject.addProperty("Uid", uid);
        jsonObject.addProperty("TimeStamp", time/1000);
        System.out.println("   jsonObject.toString()");
        // 获取response并返回
        System.out.println(jsonObject.toString());
        final Response response = given().contentType(ContentType.JSON).body(jsonObject.toString()).post(url);
        return response.body().asString();
    }

    // Post方法, 无验签
    private static String PostWithOutSignature (TestCaseEntity c, String env) {
        // 获取Case信息
        String postBody = c.getBody();
        String caseModel = c.getModule();
        String url = TestServer.getURL(caseModel, env) + c.getUrl();
        System.out.println(url+"**************************************");

        // 获取response并返回
        final Response response = given().contentType(ContentType.JSON).body(postBody).post(url);
        System.out.println(response.body().asString());
        return response.body().asString();
    }

    // NONE NOW - Get方法, 有验签
    private static String GetWithSignature (TestCaseEntity testCaseEntity, String env) {
        long time = System.currentTimeMillis();
        String signvalue = testCaseEntity.getBody();
        String signValueMD5 = converToMD5(signvalue);

        String caseModel = testCaseEntity.getModule();
        String url = TestServer.getURL(caseModel, env) + testCaseEntity.getUrl() + testCaseEntity.getBody()+"&appVer=15&"+"timestamp="+time/1000+"&"+"sign="+signValueMD5;
        System.out.println(url);
        final Response response = given().get(url);
        System.out.println(response.body().asString()+"get验签返回");
        return response.body().asString();
    }

    // Get方法, 无验签
    private static String GetWithOutSignature (TestCaseEntity c, String env) {
        // 获取Case信息
        String caseModel = c.getModule();
        String url = TestServer.getURL(caseModel, env) + c.getUrl() + c.getBody();
        String shouldBe = c.getShouldbe();
        System.out.println(url+"****************************");

        try {
            // 获取response并返回
            final Response response = given().get(url);
            System.out.println(response.body().asString()+"#################");
            return response.body().asString();
        } catch (Exception ex) {
            System.out.println(ex.getMessage()+"***************************");
            return ex.getMessage();
        }
    }

    public static String converToMD5(String md5) {
        @SuppressWarnings("deprecation")
        HashCode hashCode = Hashing.md5().hashString(md5, Charsets.UTF_8);
        String str = hashCode.toString();
        return str;
    }
    public static String userLoginReturnToken(String model, String env) {
        String Token = StringUtils.EMPTY;
        String UID = StringUtils.EMPTY;
        String findCodeURL;String getTokenURL;
        JsonObject jsonObjectCode;
        if (model.equals("记返费")){
            System.out.println("====="+model);
            findCodeURL = TestServer.getURL(model, env) + "VCodeManager/GetVCode";
            jsonObjectCode = getBodyWithSign("{\"SPhone\":\"15062201247\"}");
            getTokenURL = TestServer.getURL(model, env) + "JFF_Login/JFF_LOGN_WebLogin";
            System.out.println(getTokenURL+"-------url-------"+findCodeURL);

        }else {
            findCodeURL = TestServer.getURL(model, env) + "CM_WorkbenchLogin/WD_COMM_AskVCode";
            jsonObjectCode = getBodyWithSign("{\"LoginName\":\"tiger\"}");
            getTokenURL = TestServer.getURL(model, env) + "CM_WorkbenchLogin/WD_COMM_WorkbenchLogin";
        }
        // 获取response
        final Response response = given().contentType(ContentType.JSON).body(jsonObjectCode.toString()).post(findCodeURL);
        // 获取response中的验证码
        JsonParser jp = new JsonParser();
        JsonElement jeReturn = jp.parse(response.body().asString());
        String CodeAndMobileJson = jeReturn.getAsJsonObject().get("Data").toString();
        System.out.println(CodeAndMobileJson+"*****************");
        String LOGIN_BODY ;

        //计返费登录
        if(model.equals("记返费")){
            LOGIN_BODY = "{\"Mobile\":\"15062201247\",\"VerifyCode\":"+CodeAndMobileJson+"}";
        } else {
            LOGIN_BODY = CodeAndMobileJson;
        }
        // 获取真正的BODY体
        JsonObject jsonObjectTokenUID = getBodyWithSign(LOGIN_BODY);
        System.out.println(jsonObjectTokenUID+"==++++++++++++++");
        // 获取response
        final Response response1 = given().contentType(ContentType.JSON).body(jsonObjectTokenUID.toString()).post(getTokenURL);
        JsonElement jeReturn1 = jp.parse(response1.body().asString());
        System.out.println("jeReturn1::   "+ jeReturn1);
        // 返回Token和UID
        Token = jeReturn1.getAsJsonObject().get("Data").getAsJsonObject().get("Token").getAsString();
        if(model.equals("记返费")){
            UID = jeReturn1.getAsJsonObject().get("Data").getAsJsonObject().get("UserID").toString();
        } else {
            UID = jeReturn1.getAsJsonObject().get("Data").getAsJsonObject().get("EmployeeID").toString();
        }

        return Token + "," + UID;
    }
    // 无验签的
    private static JsonObject getBodyWithSign(String body) {
        System.out.println(body+"body");
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("AppKey", Constants.WODA_AppKey);
        jsonObject.addProperty("Data", body);
        jsonObject.addProperty("DeviceName", Constants.WODA_DeviceName);
        jsonObject.addProperty("DeviceType", Constants.WODA_DeviceType);
        jsonObject.addProperty("Lang", Constants.WODA_Lang);

        long time = System.currentTimeMillis();
        String signValue = "WDApp" + time/1000 + "" + body + "a323f9b6-1f04-420e-adb9-b06d142c5e63";
        String signValueMD5 = converToMD5(signValue);
        jsonObject.addProperty("Sign", signValueMD5);
        jsonObject.addProperty("Token", "");
        jsonObject.addProperty("Uid", "");
        jsonObject.addProperty("TimeStamp", time/1000);

        return jsonObject;
    }
}
